package com.skyz.base.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import com.skyz.base.R;

/**
 * 可以按宽高比布局的LinearLayout
 */
public class RatioLinearLayout extends LinearLayout {

    private float mRatio;

    public RatioLinearLayout(Context context) {
        this(context, null);
    }

    public RatioLinearLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RatioLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public RatioLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioLinearLayout, defStyleAttr, defStyleRes);

        if (typedArray.hasValue(R.styleable.RatioLinearLayout_ratio)) {
            final TypedValue typedValue = typedArray.peekValue(R.styleable.RatioLinearLayout_ratio);
            float ratio;
            if (typedValue.type == TypedValue.TYPE_FRACTION) {
                ratio = typedValue.getFraction(1.0f, 1.0f);
            } else {
                ratio = typedValue.getFloat();
            }
            setRatio(ratio);
        }
        typedArray.recycle();


    }

    /**
     * 修改比率
     *
     * @param ratio
     */
    public void setRatio(float ratio) {
        mRatio = ratio;
        requestLayout();
    }

    /**
     * 获取比率
     *
     * @return
     */
    public float getRatio() {
        return mRatio;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //先按标准测量一次
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //再按宽高比重新测量
        int childWidthSize = getMeasuredWidth();
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
        int childHeightSize = (int) (childWidthSize * mRatio);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
